'use strict'

const crypto = require('crypto');
const dayjs = require('dayjs');

var utc = require('dayjs/plugin/utc')
var timezone = require('dayjs/plugin/timezone');
const { type } = require('os');
dayjs.extend(utc)
dayjs.extend(timezone)

exports.splitWithTrim = (str, sep) => {
    const ret = [];
    str.split(sep).forEach(item => {
        let t = item.trim();
        if (t.length > 0) {
            ret.push(t);
        }
    })
    return ret;
}

exports.hash = (str) => {
    const hashFn = crypto.createHash('md5');
    hashFn.update(str);
    return hashFn.digest('hex');
}

function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

function replaceAll(str, match, replacement){
    return str.replace(new RegExp(escapeRegExp(match), 'g'), ()=>replacement);
}

exports.formatDate = (dateStr, utc) => {
    if (dateStr === undefined || dateStr === null || typeof dateStr !== 'string') {
        // console.log('formatDate: dateStr is invalid: ', dateStr);
        dateStr = new Date().toString(); // use current time
    }
    dateStr = replaceAll(dateStr, ' ', ' ')
    let d = dayjs(dateStr);
    if (!d.isValid()) {
        d = dayjs(new Date().toString());
    }
    if (utc && (!dateStr.endsWith('+00:00') && !dateStr.endsWith('UTC') && !dateStr.endsWith('Z'))) {
        d = d.add(8, 'hour');
    }

    return {
        valueOf: () => {
            return d.valueOf();
        },
        format: () => {
            return d.format();
        },
        formatUTC: () => {
            return d.utc().format();
        },
    }
}

exports.formatTime = (timeStr) => {
    return timeStr
}